package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.QiniuUtil;

@Controller
@RequestMapping("/upload")
public class UploadController {

	// SpringMVC把上传的信息封装到MultipartFile
	@RequestMapping("/uploadImage")
	@ResponseBody
	public JSONResult uploadImage(MultipartFile file) throws IOException {
		String newFileName = "";
		if (ImageServerUtil.IMG_SERVER == ImageServerUtil.QINIU) {
			newFileName = QiniuUtil.uploadImage(file.getBytes());
		} else if (ImageServerUtil.IMG_SERVER == ImageServerUtil.LOCAL) {
			newFileName = uploadToLocal(file);
		}
		
		return JSONResult.ok("上传成功", newFileName);
	}


	private String uploadToLocal(MultipartFile file) {
		// 702adab16e534a83ad35992b5ba30098
		String name = UUID.randomUUID().toString().replace("-", "");
		// 返回图片的名字 aa.jpg
		String fileName = file.getOriginalFilename();
		String extension = FilenameUtils.getExtension(fileName);// jpg
		// 702adab16e534a83ad35992b5ba30098.jpg
		String newFileName = name + "." + extension;
		String filePath = "D:\\pic\\" + newFileName; 
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return newFileName;
	}
	
	
	public static void main(String[] args) {
		String uuid = UUID.randomUUID().toString();
		System.out.println(uuid);// df9965e7-4f75-4f2d-89f4-b040806ae20a
		System.out.println(uuid.replace("-", ""));
	}
}
